import React from 'react';
import {Row, Col, Tabs, Icon, Input, Button, notification} from 'antd';
import "./react-bootstrap-table.min.css"
import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table';
import {updateTableMeta, updateRemCom} from "../../services/showServer";
import DicListModalContainer from '../Modal/DicListModalContainer';
import DicInfoModalContainer from '../Modal/DicInfoModalContainer';
import {colBindDic} from "../../services/dictionaryServer";
import Signals from 'signals';

//npm install react-bootstrap-table --save

const TabPane = Tabs.TabPane


class RBTableComponent extends React.Component {
  constructor(props) {
    super(props);
    //signals事件
    this.signal = new Signals.Signal();
    this.cellEditProp = {
      mode: "click",
      blurToSave: true,
      afterSaveCell: this.onAfterSaveCell.bind(this)
    };

    this.state = {
      remark: '',
      comment: '',
      editComment: '',
      partitionColumns: null,
      columns: null,
      tableMeta: null,
      table: null,
    };
  }

  componentWillMount() {
    this.signal.add(function (bind) {
      colBindDic(bind).then(function (res) {
        // 绑定成功后刷新页面数据
        if (res.status == 200) {
          this.props.listSignal.dispatch(this.state.table.id);
        } else {
          notification['error']({
            message: 'Error',
            description: '关联字典表失败，请稍后重试！',
          })
        }
      }.bind(this));
    }.bind(this));
  }

  getTime(ver) {
    var date = new Date(Number(ver));
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = date.getDate() + ' ';
    var h = date.getHours() + ':';
    var m = date.getMinutes() + ':';
    var s = date.getSeconds();
    return Y + M + D + h + m + s;
  }

  fileSize(size) {
    var kb = 1024;
    var mb = kb * 1024;
    var gb = mb * 1024;

    if (size >= gb) {
      var f = (size / gb).toFixed(2);
      return f.toString() + "GB";
    } else if (size >= mb) {
      var f = (size / mb).toFixed(2);
      return f.toString() + "MB";
    } else if (size >= kb) {
      var f = (size / kb).toFixed(2);
      return f.toString() + "KB";
    } else
      return size.toString() + "B";
  }

  //修改列信息
  onAfterSaveCell(row, cellName, cellValue) {
    var rowName = row["name"];

    //更新后的表元数据
    // var meta = this.state.tableMeta;
    var metaJson = this.state.tableMeta;
    //更新后的列信息
    for (var c in metaJson.columns) {
      if (metaJson.columns[c].name == rowName) {
        metaJson.columns[c].remark = cellValue
      }
    }

    // console.log(metaJson);
    //整体更新数据库
    var requstData = {
      "id": this.state.table.id,
      "tableMeta": JSON.stringify(metaJson)
      // "tableMeta": metaJson
    }

    // console.log(JSON.stringify(requstData));
    updateTableMeta(requstData).then(function (res) {
      //更新成功后刷新页面元数据
      if (res.status == 200) {
        this.setState({
          tableMeta: JSON.stringify(metaJson)
        });
      } else {
        notification['error']({
          message: 'Error',
          description: '更新备注失败，请稍后重试！',
        })
      }
    }.bind(this));
  }

  handleRemarkChange(e) {
    this.setState({
      remark: e.target.value,
    });
  }

  handleCommentChange(e) {
    this.setState({
      editComment: e.target.value,
    });
  }

  dicBindClick(row) {
    var tableId = this.state.table.id
    var cname = row["name"]
    // console.log("q:" + tableId + "/" + cname)
    this.refs.dicList.setState({
      tableId: tableId,
      cname: cname,
      visible: true,
    });
  }

  dicClick(row) {
    var dicId = row["dicId"]
    this.refs.dicInfo.setState({
      visible: true,
    });
    this.refs.dicInfo.initItems(dicId)
  }

  updateRemCom() {
    var requstData = {
      "id": this.state.table.id,
      "remark": this.state.remark,
      "comment": this.state.editComment
    }
    updateRemCom(requstData).then(function (res) {
      //更新成功后刷新List数据
      if (res.status == 200) {
        this.setState({
          comment: this.state.editComment,
        });
        var listData = {
          "id": this.state.table.id,
          "comment": this.state.comment
        }
        this.props.commentSignal.dispatch(listData);
      } else {
        notification['error']({
          message: 'Error',
          description: '更新表信息失败，请稍后重试！',
        })
      }
    }.bind(this));
  }

  activeDictionary(cell, row) {

    if (cell) {
      if (cell == '') {
        return (
          <Button type="primary" shape="circle" size="small" style={{border: 0}}
                  onClick={this.dicBindClick.bind(this, row)}>
            <Icon style={{color: '#F0F0F0'}} type="link"/>
          </Button>
        )
      } else {
        return (
          <div>
            <Button type="primary" shape="circle" size="small" style={{border: 0}}
                    onClick={this.dicBindClick.bind(this, row)}>
              <Icon style={{color: '#F0F0F0'}} type="link"/>
            </Button>
            <Button type="primary" shape="circle" size="small" style={{background: '#87D068', border: 0}}
                    onClick={this.dicClick.bind(this, row)}>
              <Icon style={{color: '#F0F0F0'}} type="tags"/>
            </Button>
          </div>
        );
      }
    } else {
      return (
        <Button type="primary" shape="circle" size="small" style={{border: 0}}
                onClick={this.dicBindClick.bind(this, row)}>
          <Icon style={{color: '#F0F0F0'}} type="link"/>
        </Button>
      );
    }
  }

  render() {

    const TableInfo = table => {
      if (table == null) {
        return <div></div>;
      } else {
        return (
          <div>
            <p></p>
            <Row>
              <Col span={4} style={{textAlign: "right"}}>表名：</Col>
              <Col span={20}>{this.state.table.name}</Col>
            </Row>
            <p></p>
            <Row>
              <Col span={4} style={{textAlign: "right"}}>管理员：</Col>
              <Col span={20}>{this.state.table.managerName}</Col>
            </Row>
            <p></p>
            <Row>
              <Col span={4} style={{textAlign: "right"}}>表说明：</Col>
              <Col span={20}>{this.state.comment}</Col>
            </Row>
            <p></p>
            <p></p>
            <Tabs defaultActiveKey="0">
              <TabPane tab="表信息" key="0">
                <Row>
                  <Col span={4} style={{textAlign: "right"}}>表别名：</Col>
                  <Col span={16}>
                    <Input id="remark" value={this.state.remark} onChange={this.handleRemarkChange.bind(this)}/>
                  </Col>
                  <Col span={4} style={{textAlign: "right"}}></Col>
                </Row>
                <p></p>
                <Row>
                  <Col span={4} style={{textAlign: "right"}}>管理员：</Col>
                  <Col span={16}>{this.state.table.managerName}</Col>
                  <Col span={4} style={{textAlign: "right"}}></Col>
                </Row>
                <p></p>
                <Row>
                  <Col span={4} style={{textAlign: "right"}}>物理地址：</Col>
                  <Col span={16}>{this.state.tableMeta.location}</Col>
                  <Col span={4} style={{textAlign: "right"}}></Col>
                </Row>
                <p></p>
                <Row>
                  <Col span={4} style={{textAlign: "right"}}>拥有者：</Col>
                  <Col span={16}>{this.state.tableMeta.owner}</Col>
                  <Col span={4} style={{textAlign: "right"}}></Col>
                </Row>
                <p></p>
                <Row>
                  <Col span={4} style={{textAlign: "right"}}>最小文件大小：</Col>
                  <Col span={16}>{this.fileSize(this.state.tableMeta.minFileSize)}</Col>
                  <Col span={4} style={{textAlign: "right"}}></Col>
                </Row>
                <p></p>
                <Row>
                  <Col span={4} style={{textAlign: "right"}}>最大文件大小：</Col>
                  <Col span={16}>{this.fileSize(this.state.tableMeta.maxFileSize)}</Col>
                  <Col span={4} style={{textAlign: "right"}}></Col>
                </Row>
                <p></p>
                <Row>
                  <Col span={4} style={{textAlign: "right"}}>总文件大小：</Col>
                  <Col span={16}>{this.fileSize(this.state.tableMeta.totalFileSize)}</Col>
                  <Col span={4} style={{textAlign: "right"}}></Col>
                </Row>
                <p></p>
                <Row>
                  <Col span={4} style={{textAlign: "right"}}>总文件数：</Col>
                  <Col span={16}>{this.state.tableMeta.totalNumberFiles}</Col>
                  <Col span={4} style={{textAlign: "right"}}></Col>
                </Row>
                <p></p>
                <Row>
                  <Col span={4} style={{textAlign: "right"}}>最近更新时间：</Col>
                  <Col span={16}>{this.getTime(this.state.tableMeta.lastUpdateTime)}</Col>
                  <Col span={4} style={{textAlign: "right"}}></Col>
                </Row>
                <p></p>
                <Row>
                  <Col span={4} style={{textAlign: "right"}}>表说明：</Col>
                  <Col span={16}>
                    <Input id="comment" type="textarea" rows={4} defaultValue={this.state.comment}
                           value={this.state.editComment}
                           onChange={this.handleCommentChange.bind(this)}/>
                  </Col>
                  <Col span={4} style={{textAlign: "right"}}></Col>
                </Row>
                <p></p>
                <Row>
                  <Col span={12} offset={4}>
                    <Button type="primary" onClick={this.updateRemCom.bind(this)}>保存</Button>
                  </Col>
                  <Col span={8} style={{textAlign: "right"}}></Col>
                </Row>
              </TabPane>

              <TabPane tab="列信息" key="1">
                <Row>
                  <Col span={24}>
                    <BootstrapTable data={ this.state.columns } cellEdit={this.cellEditProp} pagination={true}>
                      <TableHeaderColumn dataField='name' isKey={ true } width='200'>列名</TableHeaderColumn>
                      <TableHeaderColumn dataField='type' editable={false} width='100'>类型</TableHeaderColumn>
                      <TableHeaderColumn dataField='remark'>备注</TableHeaderColumn>
                      <TableHeaderColumn dataField='dicId' editable={false}
                                         dataFormat={ this.activeDictionary.bind(this) }
                                         width='75'>字典</TableHeaderColumn>
                    </BootstrapTable>
                  </Col>
                </Row>
              </TabPane>

              <TabPane tab="分区信息" key="2">
                <Row>
                  <Col span={24}>
                    <BootstrapTable data={ this.state.partitionColumns } pagination={true}>
                      <TableHeaderColumn dataField='name' isKey={ true }>分区名</TableHeaderColumn>
                      <TableHeaderColumn dataField='type' editable={false}>类型</TableHeaderColumn>
                    </BootstrapTable>
                  </Col>
                </Row>
              </TabPane>
            </Tabs>
            <DicListModalContainer ref="dicList" signal={this.signal}></DicListModalContainer>
            <DicInfoModalContainer ref="dicInfo"></DicInfoModalContainer>
          </div>
        );
      }
    };

    const tableInfo = TableInfo(this.state.table);

    return (
      <div>
        {tableInfo}
      </div>
    );
  }
}

export default RBTableComponent;

